package com.cat.greedyAlgorithm;

import java.util.HashMap;
import java.util.Locale;

/**
 * @author 曲大人的喵
 * @description https://leetcode.cn/problems/longest-balanced-substring-ii/
 * @create 2025/10/12 19:59
 * @since JDK17
 */

public class Solution88 {
    char[] s;
    int n;

    int m1() {
        int ans = 0, x = 0;
        for (int i = 0; i < n; i++) {
            if (i == 0 || s[i - 1] == s[i]) {
                x++;
            } else {
                x = 1;
            }
            ans = Math.max(ans, x);
        }
        return ans;
    }

    int m2(char a, char b) {
        HashMap<Integer, Integer> map = new HashMap<>();
        map.put(0, -1);
        int x = 0, y = 0, ans = 0;
        for (int i = 0; i < n; i++) {   //
            if (s[i] == a) {
                x++;
            } else if (s[i] == b) {
                x--;
            } else {
                map.clear();
                x = 0;
            }
            if (map.containsKey(x)) {   // 之前出现过
                ans = Math.max(ans, i - map.get(x));
            } else {
                map.put(x, i);
            }
        }

        return ans;
    }
    int m3() {
        HashMap<Long, Integer> map = new HashMap<>();
        map.put(0L, -1);
        int ans = 0, x = 0, y = 0;
        for (int i = 0; i < n; i++) {
            if (s[i] == 'a') {
                x++;
            } else if (s[i] == 'b') {
                x--;
                y++;
            } else {
                y--;
            }
            long key = x * 2 * n + y;
            if (map.containsKey(key)) {
                ans = Math.max(ans, map.get(key));
            } else {
                map.put(key, i);
            }
        }
        return ans;
    }

    public int longestBalanced(String s) {
        this.s = s.toCharArray();
        n = s.length();
        int ans = 0;
        ans = Math.max(ans, m1());
        ans = Math.max(ans, m2('a', 'b'));
        ans = Math.max(ans, m2('a', 'c'));
        ans = Math.max(ans, m2('b', 'c'));
        ans = Math.max(ans, m3());
        return ans;
    }
}
